using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace SPDevExplorer
{
    [Serializable]
    public class ExplorerSettings
    {
        private static readonly Dictionary<string, ExplorerSettings> _settingObjects =
            new Dictionary<string, ExplorerSettings>();

        private static XmlDocument _globalSettings = null;

        private readonly XmlElement _settings;

        private ExplorerSettings(XmlElement settings)
        {
            _settings = settings;
        }

        public string WorkingFolder
        {
            get
            {
                string sWorkingFolder = GlobalWorkingFolder;
                if (!string.IsNullOrEmpty(_settings.GetAttribute("WorkingFolder")))
                    sWorkingFolder = _settings.GetAttribute("WorkingFolder");
                else
                {
                    string sUrl = _settings.GetAttribute("Url");
                    sUrl = sUrl.Substring(sUrl.IndexOf("//") + 2);

                    sWorkingFolder += sUrl.Replace(":", "");
                }

                // SvdO: Change forward slashes into backward slashes
                sWorkingFolder = sWorkingFolder.Replace("/", "\\");

                return sWorkingFolder + (sWorkingFolder.EndsWith("\\") ? "" : "\\");
            }
            set { _settings.SetAttribute("WorkingFolder", value); }
        }

        public static string GlobalWorkingFolder
        {
            get
            {
                string sPath = Application.UserAppDataPath;
                sPath = sPath.Substring(0, sPath.LastIndexOf("Microsoft Corp")) + "SPDevExplorer";

                if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);

                return sPath + "\\";
            }
        }

        public static XmlElement PreviousSites
        {
            get
            {
                EnsureGlobalSettings();
                return (XmlElement) _globalSettings.DocumentElement.SelectSingleNode("PreviousSites");
            }
        }

        public static bool WssInstalled
        {
            get
            {
                try
                {
                    // Test for both Office 12 and Office 14 (Wss3/Wss4)
                    Microsoft.Win32.RegistryKey k12 =
                        Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                            "SOFTWARE\\Microsoft\\Shared Tools\\Web Server Extensions\\12.0\\WSS");
                    if (k12 != null) return true;

                    Microsoft.Win32.RegistryKey k14 =
                        Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                            "SOFTWARE\\Microsoft\\Shared Tools\\Web Server Extensions\\14.0\\WSS");
                    if (k14 != null) return true;

                    return false;
                }
                catch
                {
                    return false;
                }
            }
        }

        public static ExplorerSettings Current(string projectUrl)
        {
            if (!_settingObjects.ContainsKey(projectUrl.ToLower()))
            {
                EnsureGlobalSettings();

                XmlElement oSettings =
                    (XmlElement)
                    _globalSettings.DocumentElement.SelectSingleNode("Settings[@Url='" + projectUrl.ToLower() + "']");

                if (oSettings == null)
                {
                    oSettings = _globalSettings.CreateElement("Settings");
                    oSettings.SetAttribute("Url", projectUrl.ToLower());
                }

                _settingObjects.Add(projectUrl.ToLower(), new ExplorerSettings(oSettings));
            }

            return _settingObjects[projectUrl.ToLower()];
        }

        private static void EnsureGlobalSettings()
        {
            if (_globalSettings == null)
            {
                _globalSettings = new XmlDocument();
                if (File.Exists(GlobalWorkingFolder + "settings.xml"))
                    _globalSettings.Load(GlobalWorkingFolder + "settings.xml");
                else
                    _globalSettings.LoadXml("<GlobalSettings><PreviousSites/></GlobalSettings>");
            }
        }

        public static ExplorerSettings Current(TreeNode node)
        {
            while (node.Parent != null) node = node.Parent;

            FolderProperties fp = new FolderProperties(node);
// SvdO: node.Text now contains full url, don't prefix with http://
#if false
            return Current("http://" + node.Text);
#else
            return Current(node.Text);
#endif
// /SvdO
        }

        public static void Save()
        {
            _globalSettings.Save(GlobalWorkingFolder + "settings.xml");
        }
    }
}